import React from 'react'
import ReactDOM from 'react-dom'     
// import jsSHA from 'jssha' 
import  List from '../../component/List/List'//list
import * as DataHandler from './DataHandler' 
import './css/Weather.css' 

class Weather extends React.Component {
    constructor(props) {
        super(props);
        this.state = {   
            
        };
    } 

     info={
        boxW: document.documentElement.clientWidth || document.body.clientWidth,
        boxH: document.documentElement.clientHeight || document.body.clientHeight,
        curInfoDetailH:210,   
    }  
    // 对象转字符串
    raw =  (args) => {
            let  keys = Object.keys(args);
            keys = keys.sort()
            let  newArgs = {};
            keys.forEach(function (key) {
                newArgs[key.toLowerCase()] = args[key];
            });

            let  string = '';
            for (let  k in newArgs) {
                string += '&' + k + '=' + newArgs[k];
            }
            string = string.substr(1);
            return string;
        };

     componentWillMount = () => {  
  
      } 
     componentDidMount = () => {   
        // 百度地图API功能
            let map = new BMap.Map("allmap"); 
          let that =this;
            let myCity = new BMap.LocalCity(); 
            let geolocation = new BMap.Geolocation(); 
            geolocation.getCurrentPosition(function(r){
                if(this.getStatus()== BMAP_STATUS_SUCCESS){  
                    let rp = new BMap.Point(r.point.lng,r.point.lat);  
                    let gc = new BMap.Geocoder();  
                    gc.getLocation(rp,function(rs){  
                        let addComp = rs.addressComponents;   
                        addComp.city = addComp.province == "福建省" ? addComp.city :"福州市";//不是福建省的 就是福州市
                        that.getData('weather',{city:addComp.city}) ;//获取数据 
                        document.title=addComp.city+'天气预报';  
                  });   
                }
            });  
    }  
 
    // 数据请求
    getData = (key,par) =>{ 
        let that =this;
        T.ajax({
        key: key,
        data: par,
        success: function success(result) {
            switch(key){
                case "token":
                    that.info.access_token = result.access_token;
                             this.getData('jsapi_ticket',{
                                access_token:that.info.access_token,
                                type:'jsapi'
                            })
                break;
                case "jsapi_ticket": 
                     that.info.jsapi_ticket = result.ticket;   
                break;
                case 'weather':
                        let results = typeof(result)=='string'? JSON.parse(result):result;
                        let data = results.data?results.data:[];//可能是错误的，提示无数据
                        that.proDataFn(data); 
                break;
            }
     
            }
        });
    }
    proDataFn=(data)=>{    
        let temp=[ ];
        let index=0;
        data.map((item,i)=>{  
            if(item.ampm==0){//白天
                temp[index]={};
                temp[index].bticon =  '../attendance/assets/weather/'+ item.tx+'big.png'; 
                temp[index].btqw =   item.qw ; 
                temp[index].tm = item.ybtm.replace(/(\d{4})-(\d{2})-(\d{2})T(.*)/,"$2/$3");  
                  temp[index].data=[];
                  temp[index].data.push({
                      tm : item.ybtm.replace(/(\d{4})-(\d{2})-(\d{2})T(.*)/,"$2/$3"),
                      qw: item.qw+'℃',
                      icon: '../attendance/assets/weather/'+ item.tx+'big.png',
                        tx:item.tx,
                      fl: item.fl,
                      fx: item.fx,
                  })
              
            }else{//晚上
                temp[index].wsicon =  '../attendance/assets/weather/'+ item.tx+'big.png'; 
                temp[index].wsqw =   item.qw ; 
                temp[index].data.push({
                      tm : item.ybtm.replace(/(\d{4})-(\d{2})-(\d{2})T(.*)/,"$2/$3"),
                      qw: item.qw+'℃',
                      icon: '../attendance/assets/weather/'+ item.tx+'big.png',
                      fl: item.fl,
                      tx:item.tx,
                      fx: item.fx,
                  })
                  index++;
            }
           
        })
        this.listData =temp;
        this.itemClick(0);//默认打开第一个
        this.setState({})
    }
     listConfig = {
        width:   document.documentElement.clientWidth || document.body.clientWidth,
        theme:'default',  
        dataConfig:[  
              {
                key:'tm',
                itemStyle:{  textAlign: 'left', width: '35% ' },
            },{
                key:'bticon',
                type:'img',
                itemStyle:{width:'10%'}          
            },{
                key:'wsicon',
                type:'img',
                itemStyle:{  width:'10%', 'marginLeft': '15px'}, 
            },{
                key:'btqw',
                itemStyle:{   textAlign: 'right', width: '35% ' ,}, 
            },{
                key:'wsqw',
                itemStyle:{   textAlign: 'right',   }, 
            }
        ] 
    }
    listData=[ 
        {
            tm:'12/21',
            bticon:'晴',
            btqw:19,
            wsicon:'阴',
            wsqw:5,
            data:[
            //     {
            //     "qw": 19,
            //     "fx": "无持续风向",
            //     "fl": "微风",
            //     "tx": "晴",
            //     "ampm": 0,
            //     "ybtm": "2017-12-07T00:00:00"
            // },{
            //     "qw": 5,
            //     "fx": "无持续风向",
            //     "fl": "微风",
            //     "tx": "阴",
            //     "ampm": 1,
            //     "ybtm": "2017-12-07T00:00:00"
            // }
            ]
        } ]

    itemClick = (i) => {   
        // let obj = event.target.nodeName == "IMG" ? event.target.parentElement.parentElement :event.target.parentElement ;
        let obj =document.getElementsByClassName("listWrap")[0].children[i].children[1]
        obj.style.display = obj.style.display=='flex' ? 'none': 'flex'; 
        // obj.nextElementSibling.style.display = obj.nextElementSibling.style.display=='flex' ? 'none': 'flex'; 
    }
    render() {  
        return (
            <div  className="Weather" style ={{height:this.info.boxH  }}>  
              <div className='wrap'>  
                    <div ref='listwrap' className= 'listWrap' >
                        {
                            this.listData.map((item,i)=>{  
                                return (
                                    <div className="item"   onClick={() =>this.itemClick(i)}>  
                                            <div className ='showarea'>
                                                {
                                                    this.listConfig.dataConfig.map((jtem,j)=>{  
                                                
                                                        let showarea = jtem.type == 'img'?  <img src= {item[jtem.key]} / > : item[jtem.key] ;   
                                                        let str =  jtem.key == 'btqw'? <span style={{display:'inline-block',marginRight:'5px'}}>/ </span>: ''; 
                                                        if( item['wsicon'] ==  item['bticon']  ){  //白天和晚上的天气一样
                                                            let w = jtem.key=='tm' ||  jtem.key=='btqw'? parseInt(jtem.itemStyle.width.replace('%',''))+10+'%' : jtem.itemStyle.width ;
                                                            if(jtem.key !='wsicon' ){
                                                                    return (
                                                                        <span  style={{width:w,textAlign:jtem.key == 'tm' ? 'left' : 'right', paddingRight:jtem.key=='low'? '20px':'', paddingLeft:jtem.key=='tm'? '20px':''}}  >
                                                                            {showarea}  {str}
                                                                        </span>
                                                                    )  
                                                            }
                                                            
                                                        }else{
                                                            jtem.itemStyle.paddingRight = jtem.key=='wsqw'? '20px':'';
                                                            jtem.itemStyle.paddingLeft = jtem.key=='tm'? '20px':''
                                                                return (
                                                                    <span style={jtem.itemStyle}  >
                                                                        {showarea}  {str}
                                                                    </span>
                                                                )  
                                                        }  
                                                    })
                                                }  
                                            </div>
                                            <div className = 'curInfoDetail' style={{height:this.info.curInfoDetailH}}>
                                            {
                                                item.data.map((ktem,i) => { 
                                                    return (
                                                        <div  >
                                                            <div>{ktem.tm}</div>
                                                            <div>{ktem.qw}</div>
                                                            <div style={{    width: item.data.length > 1? '56%' : '30%',  margin: 'auto'}}><img src={ktem.icon} alt="" /><span>{ktem.tx}</span></div> 
                                                            <div>{ktem.fx} &nbsp; {ktem.fl}</div> 
                                                        </div>
                                                    )
                                                })
                                            }
                                        </div>
                                    </div>
                                )
                            })
                        }
                    </div> 
              </div>
            </div>
        )
    }
} 
export default Weather 